#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>
#pragma comment(lib,"ws2_32.lib")
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;

#define MY_PORT 165226

typedef struct socket_counter
{
    SOCKET send_socket;
    char buffer[1024];
}socket_counter;

void my_wc(socket_counter *my_counter);
int main()
{
    SOCKET listen_socket;//声明Socket接口变量
    struct sockaddr_in my_addr;//声明Socket地址变量
    int dummy,rev_length;
    //char buffer[1024];
    char file_name[100];
    pthread_t t;
    socket_counter *my_counter;

    WSADATA wsaDate;

    WSAStartup(MAKEWORD(1,1),&wsaDate);//启动版本

    listen_socket=socket(AF_INET,SOCK_STREAM,0);//声明为IPV4的TCP

    my_addr.sin_family=AF_INET;//IPV4
    my_addr.sin_port=htons(MY_PORT);//端口
    my_addr.sin_addr.s_addr=htonl(INADDR_ANY);//可以连接任一电脑

    dummy = sizeof(SOCKADDR);
    memset(file_name,0,sizeof(file_name));

    if( bind(listen_socket,(struct sockaddr*)&my_addr,sizeof(struct sockaddr))<0)//绑定本地IP与Socket
    {
       printf("Server Bind error!\n");
    }

    if(listen(listen_socket,5)<0)//等待序列，默认队列最多为5个请求
    {
        printf("Server Listen error!\n");
    }

    while(1)
    {
        my_counter->send_socket=accept(listen_socket,NULL,&dummy);//listen函数创建等待队列后，accept函数处理客户端发来的连接请求
        if(my_counter->send_socket==-1)
        {
            printf("Server Accept failed!\n");
            break;
        }
        printf("Accept success!\n");
        pthread_create(&t, NULL, &my_wc,my_counter);
        pthread_join(&t, NULL);
    }
    closesocket(listen_socket);//依次关闭连接
    WSACleanup();//清除
    return 0;
}
void my_wc(socket_counter *my_counter){
    pthread_mutex_lock( &counter_mutex );
    int len, i;
    long wordscount=0;
    int flag=1;
    while(1)
    {
        if((len=recv(my_counter->send_socket, my_counter->buffer, 1024, 0))>0)
        {
            for(i=0; i<len; i++)
            {
                if(flag==0)
                {
                    switch(my_counter->buffer[i])
                    {
                        case ' ':
                            wordscount++;
                            break;
                        case '\n':
                            wordscount++;
                            break;
                        case '\r':
                            wordscount++;
                            break;
                        default:
                            break;
                    }
                }
                if(my_counter->buffer[i]== ' ' || my_counter->buffer[i]=='\n' || my_counter->buffer[i]=='\r')
                    flag=1;
                else
                    flag=0;
            }
        }
        if(len<1024) break;
    }
    send(my_counter->send_socket, &wordscount, sizeof(long), 0);
    close(my_counter->send_socket);
    pthread_mutex_unlock( &counter_mutex );
}
